package com.sychip.fhc.app.wsn.screen

// import androidx.compose.ui.semantics.isTraversalGroup
// import androidx.compose.ui.semantics.semantics
// import androidx.compose.ui.semantics.traversalIndex
// //Jetpack Compose的无障碍功能实现和焦点控制

import android.content.res.Configuration
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fhc.base.isTablet
import com.fhc.base.ymdHMS
import com.fhc.view.dialog.FhcConfirmDialog
import com.fhc.view.list.ClickableListItem
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.util.perColor
import com.sychip.fhc.app.wsn.common.util.rssiColor
import com.sychip.fhc.app.wsn.nav.PostToWsnDetail
import com.sychip.fhc.app.wsn.nav.WsnNavigationItem.NavItem_List
import com.sychip.fhc.app.wsn.nav.WsnTabNavigationActions
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.delay

@Composable
fun WsnListScreen(navController: NavHostController = rememberNavController()) {
    val navBackStackEntry = remember { navController.currentBackStackEntry }
    val viewModel: WsnListViewModel = navBackStackEntry?.let { hiltViewModel(it) } ?: hiltViewModel()

    // 1. 状态管理
    var isTilted by remember { mutableStateOf(false) }
    val alphaTilted by animateFloatAsState(if (isTilted) 0.7f else 1f)
    val scaleTilted by animateFloatAsState(if (isTilted) 0.9f else 1f)

    val rssiAllFlow by viewModel.rssiAllFlow.collectAsStateWithLifecycle()
    val rssiFilterFlow by viewModel.rssiFilterFlow.collectAsStateWithLifecycle()
    val animationSpec: AnimationSpec<Float> = if (rssiAllFlow.dataList.isEmpty()) {
        keyframes {
            durationMillis = 800
            1f at 0 // 0-300ms保持1
            1f at 500 // 500ms时仍为1
            0f at 800 // 500-800ms过渡到0
        }
    } else {
        tween(durationMillis = 300)
    }
    val alphaHidden by animateFloatAsState(
        if (rssiAllFlow.dataList.isEmpty()) 0f else 1f,
        animationSpec = animationSpec
    )
    val showDeleteDialog = remember { mutableStateOf(false) }
    if (showDeleteDialog.value) {
        FhcConfirmDialog(
            appIcon = R.mipmap.ic_launcher,
            title = stringResource(R.string.wsn_q_delete_all_data),
            message = stringResource(R.string.wsn_q_delete_all_data_msg),
            onPositiveClick = {
                isTilted = true
                viewModel.clearAllData()
                showDeleteDialog.value = false
            },
            onNegativeClick = {
                showDeleteDialog.value = false
            }
        )
    }

    var showFilter by remember { mutableStateOf(true) }
    val filterState by viewModel.filterState.collectAsStateWithLifecycle()
    val isFilterExpanded = remember { mutableStateOf(false) }
    var filterResult by remember { mutableStateOf("") }
    LaunchedEffect(key1 = rssiAllFlow.dataList, key2 = rssiFilterFlow.size, key3 = filterState) {
        filterResult = if (filterState.isFilterDevIds || filterState.isFilterRssi) {
            " ${rssiFilterFlow.size} / ${rssiAllFlow.dataList.size} "
        } else {
            " ${rssiAllFlow.dataList.size} "
        }
    }

    val blurRadius by animateIntAsState(
        targetValue = if (isFilterExpanded.value) 6 else 0,
        animationSpec = tween(durationMillis = 300),
        label = "blur_animation"
    )

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            FhcTopAppBar(
                title = NavItem_List.label,
                actions = {
//                    IconButton(onClick = {
//                        showFilter = !showFilter
//                        if(!showFilter){
//                            isFilterExpanded.value = false
//                        }
//                    }) {
//                        Box {
//                            Icon(
//                                if(showFilter) Icons.Filled.FilterAlt else Icons.Filled.FilterAltOff,
//                                contentDescription = null,
//                                tint = colorScheme.onPrimary
//                            )
//                        }
//                    }
                }
            )
        },
        floatingActionButton = {
            // 2. 旋转动画定义
            val rotation by animateFloatAsState(
                targetValue = if (isTilted) 45f else 0f,
                animationSpec = spring(
                    dampingRatio = 0.4f,
                    stiffness = 100f
                ),
                label = "tilt_animation",
                finishedListener = {
                    if (isTilted) {
                        // 倾倒完成后触发恢复动画
                        isTilted = false
                    }
                }
            )

            // 3. 自动恢复逻辑
            LaunchedEffect(isTilted) {
                if (isTilted) {
                    delay(400)
                    isTilted = false
                }
            }
            FloatingActionButton(
                onClick = {
                    isFilterExpanded.value = false
                    if (!showDeleteDialog.value) {
                        showDeleteDialog.value = true
                    }
                },
                modifier = Modifier.rotate(rotation).alpha(alphaTilted).alpha(alphaHidden).scale(scaleTilted),
                containerColor = colorScheme.primary, // 红色背景
                contentColor = colorScheme.onPrimary,
                shape = CircleShape
            ) {
                Icon(Icons.Outlined.Delete, stringResource(id = R.string.edit_task))
            }
        }
    ) { innerPadding ->

        Box(modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxSize()) {
            Box(
                modifier = Modifier.fillMaxSize().then(
                    if (isFilterExpanded.value) {
                        Modifier.blur(
                            blurRadius.dp,
                            BlurredEdgeTreatment.Unbounded
                        )
                    } else {
                        Modifier
                    }
                )
            ) {
                RssiDataListView(
                    viewModel = viewModel,
                    modifier = Modifier.fillMaxSize().padding(
                        top = if (!rssiAllFlow.dataList.isEmpty() && showFilter) FilterHeight else 0.dp
                    ),

                    navController = navController
                )
            }
            if (!rssiAllFlow.dataList.isEmpty() && showFilter) {
                MultipleFilterRow(
                    isExpanded = isFilterExpanded,
                    filter = filterState,
                    filterResult = filterResult,
                    onFilterCollapseStart = { collapse ->
                    },
                    onFilterCollapseStop = { collapse ->
                    },
                    onFilterChanged = { newFilter ->
                        viewModel.updateFilterDto(newFilter)
                    }
                )
            }
        }
    }
}
@Composable
private fun RssiAvgPerRow(it: WsnListViewModel.MapDeviceRssiDto){

    val rssi = buildAnnotatedString {
        withStyle(style = SpanStyle(color = colorScheme.onPrimaryContainer, fontSize= MaterialTheme.typography.bodyLarge.fontSize)) {
            append("RSSI: ")
        }
        withStyle(style = SpanStyle(color = it.rssi.rssiColor(), fontSize= MaterialTheme.typography.bodyMedium.fontSize)) {
            append(it.rssi.toString())
        }
    }
    val avg = buildAnnotatedString {
        withStyle(style = SpanStyle(color = colorScheme.onPrimaryContainer, fontSize= MaterialTheme.typography.bodyLarge.fontSize)) {
            append("AVG: ")
        }
        withStyle(style = SpanStyle(color = it.avg.rssiColor(colorScheme.onPrimaryContainer), fontSize= MaterialTheme.typography.bodyMedium.fontSize)) {
            append(it.avg)
        }
    }
    val per = buildAnnotatedString {
        withStyle(style = SpanStyle(color = colorScheme.onPrimaryContainer, fontSize= MaterialTheme.typography.bodyLarge.fontSize)) {
            append("PER: ")
        }
        withStyle(style = SpanStyle(color = it.per.perColor(colorScheme.onPrimaryContainer), fontSize= MaterialTheme.typography.bodyMedium.fontSize)) {
            append(it.per+"%")
        }
    }

    Row(modifier = Modifier.width(260.dp)){
        Text(
            modifier = Modifier.weight(1f),
            text = rssi
        )
        Text(
            modifier = Modifier.weight(1f),
            text = avg
        )
        Text(
            modifier = Modifier.weight(1f),
            text = per
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun RssiDataListView(
    modifier: Modifier = Modifier,
    viewModel: WsnListViewModel,
    navController: NavHostController = rememberNavController()
) {

    val rssiAll by viewModel.rssiAllFlow.collectAsStateWithLifecycle()
    val rssiFilter by viewModel.rssiFilterFlow.collectAsStateWithLifecycle()


    if (rssiAll.dataList.isEmpty()) {
        RssiEmptyView(modifier = modifier)
    } else {
        val navActions: WsnTabNavigationActions = remember(navController) { WsnTabNavigationActions(navController) }

        Column(Modifier.fillMaxSize()) {
//            SearchBar(
//                modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = 0.dp),
//                windowInsets = WindowInsets(0.dp),
//                inputField = {
//                    SearchBarDefaults.InputField(
//                        query = searchQuery,
//                        onQueryChange = { viewModel.updateFilter(it) },
//                        onSearch = { focusManager.clearFocus() },
//                        expanded = false,
//                        onExpandedChange = {   },
//                        placeholder = { Text(stringResource(R.string.wsn_info_input_dev_id)) },
//                        leadingIcon = { Icon(Icons.Default.Search, contentDescription = null,
//                            modifier = Modifier.clickable {
//                                focusManager.clearFocus()
//                            }) },
//                        trailingIcon = {
//                            if (!searchQuery.isEmpty()) {
//                                Icon(
//                                    Icons.Default.Close, contentDescription = null,
//                                    modifier = Modifier.clickable {
//                                        viewModel.updateFilter("")
//                                        focusManager.clearFocus()
//                                    })
//                            }
//                        },
//                    )
//                },
//                expanded = false,
//                onExpandedChange = {  },
//            ) {
//
//            }

            val config = LocalConfiguration.current
            if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                LazyVerticalGrid(
                    columns = GridCells.Fixed(2),
                    modifier = modifier,
                    contentPadding = PaddingValues(8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(rssiFilter.size,  key = { rssiFilter[it].fromDevId + rssiFilter[it].toDevId  }) { it ->
                        val dto = rssiFilter[it]

                        Card(colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))) {
                            ClickableListItem(
                                item = dto,
                                itemView = {
                                    WsnRssiDataListItem(dev = it) {
                                        RssiAvgPerRow(it)
                                    }
                                },
                                onClick = {
                                    val param = PostToWsnDetail(dto.fromDevId, dto.toDevId, 0L, 0L)
                                    navActions.navigateToWsnListDetail(param)
                                    MainApplication.instance().showBottomNavbar(false)
                                }
                            )
                        }
                    }
                }
            } else {

                LazyColumn(
                    modifier = modifier,
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 16.dp),
                ) {
                    items(
                        count = rssiFilter.size,
                        key = { rssiFilter[it].fromDevId + rssiFilter[it].toDevId }
                    ) { it ->
                        val dto = rssiFilter[it]
//                        Timber.i("LazyColumn  fromDevId %s  %s   %s   %s  ",dto.fromDevId,dto.toDevId,avgPer?.avg,avgPer?.per)
                        ClickableListItem(
                            item = dto,
                            itemView = {
                                WsnRssiDataListItem(dev = it) {
                                    RssiAvgPerRow(it)
                                }
                            },
                            onClick = {
                                val param = PostToWsnDetail(
                                    dto.fromDevId,
                                    dto.toDevId,
                                    0L,
                                    0L
                                )
                                navActions.navigateToWsnListDetail(param)
                                MainApplication.instance().showBottomNavbar(false)
                            }
                        )
                        // 添加分隔线
                        HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
                    }
                }
            }
        }
    }
}

@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true)
@Composable
private fun WsnRssiDataListItem(
    modifier: Modifier = Modifier,
    dev: WsnListViewModel.MapDeviceRssiDto = WsnListViewModel.MapDeviceRssiDto(),
    extras: @Composable () -> Unit = {},
) {
    val config = LocalConfiguration.current

    if (config.orientation == Configuration.ORIENTATION_PORTRAIT && !isTablet()) {
        Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
            Box(modifier = Modifier.size(30.dp, 30.dp).clip(RoundedCornerShape(15.dp)).background(dev.rssi.rssiColor()))
            Spacer(modifier = Modifier.width(16.dp))
            Column(
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = "${dev.fromDevId} -->  ${dev.toDevId}",
                    color = colorScheme.onPrimaryContainer,
                    style = MaterialTheme.typography.titleMedium
                )
                Spacer(modifier = Modifier.height(8.dp))
                extras()
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    modifier = Modifier.fillMaxWidth(),
                    text = dev.dateTime.ymdHMS(),
                    textAlign = TextAlign.End,
                    color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }else{
        Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
//        CircularIcon(Icons.Default.Bluetooth,modifier = Modifier.size(36.dp, 36.dp))
            Box(modifier = Modifier.size(30.dp, 30.dp).clip(RoundedCornerShape(15.dp)).background(dev.rssi.rssiColor()))
            Spacer(modifier = Modifier.width(16.dp))
            Column(
                modifier = Modifier.fillMaxWidth().weight(1f)
            ) {
                Text(
                    text = "${dev.fromDevId} -->  ${dev.toDevId}",
                    color = colorScheme.onPrimaryContainer,
                    style = MaterialTheme.typography.titleMedium
                )
                Spacer(modifier = Modifier.height(8.dp))
                Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        modifier = Modifier.weight(1f),
                        text = dev.dateTime.ymdHMS(),
                        color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
            extras()
        }
    }
}
